//
//  UIButton+loadNetImage.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/5/8.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "UIButton+loadNetImage.h"
#import "BiUtil.h"
@implementation UIButton (loadNetImage)

-(void)reloadImage:(NSString *)url{
    if (!url||[url isEqual:[NSNull null]] || [url isEqualToString:@"<null>"] || url.length==0) {
        [self setBackgroundImage:nil forState:UIControlStateNormal];
        return;
    }
    NSString *url_ =[NSString stringWithFormat:@"%@%@",SERVICE_URL_FORMAL,url];
    
    NSString *localPath = [NSString stringWithFormat:@"%@/%@",[BiUtil tempImageFilePath],[url lastPathComponent]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
        
        [self setBackgroundImage:[UIImage imageWithContentsOfFile:localPath] forState:UIControlStateNormal];

    }else {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url_]];
        [request setHTTPMethod:@"POST"];
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *response,
                                                   NSData *data,
                                                   NSError *error){
                                   if (data) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           UIImage *downLoadImage = [UIImage imageWithData:data];
//                                           if (downLoadImage.size.width >110 ) {
//                                               
//                                               downLoadImage  =[BiUtil scaleToSize:downLoadImage size:CGSizeMake(110,  downLoadImage.size.height*110/downLoadImage.size.width)];
//                                           }
                                           [self setBackgroundImage:downLoadImage forState:UIControlStateNormal];
                                           [self setNeedsDisplay];
                                           [self setNeedsLayout];
                                           dispatch_queue_t bgque = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                                           dispatch_async(bgque, ^{[data writeToFile:localPath atomically:YES];});
                                           
                                       });
                                   }
                                   
                               }];
    }
}


@end
